package com.bh.common.utils.pdf;

import com.bh.common.config.BhtmsConfig;
import com.bh.common.exception.UtilException;
import com.bh.common.utils.spring.SpringUtils;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

/**
 * pdf跑龙套
 *
 * @author shuangluxing@163.com
 * @date 2023/03/28
 */
@Component
public class PdfUtils {
    private static final Logger log = LoggerFactory.getLogger(PdfUtils.class);

    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @return 结果
     */
    public String exportPdfFile(String tempFileName, Map<String, Object> data) {
        // 渲染HTML模板
        String html = SpringUtils.getBean(SpringTemplateEngine.class).process("pdf_temp/" + tempFileName + ".html", new Context(Locale.getDefault(), data));
        // 导出PDF
        OutputStream out;
        try {
            byte[] fileData = htmlToByte(html);
            String filename = encodingFilename(tempFileName);
            out = new FileOutputStream(getAbsoluteFile(filename));
            //返回一个字节数组文件的内容
            out.write(fileData);
            out.close();
            return filename;
        } catch (Exception e) {
            log.error("导出PDF异常{}", e.getMessage());
            throw new UtilException("导出PDF失败，请联系网站管理员！");
        }
    }

    public void exportPdfByte(HttpServletResponse response, String tempFileName, Map<String, Object> data) {
        // 渲染HTML模板
        String html = SpringUtils.getBean(SpringTemplateEngine.class).process("pdf_temp/" + tempFileName + ".html", new Context(Locale.getDefault(), data));
        try {
            byte[] bytes = htmlToByte(html);
            response.reset();
            response.setContentType("application/pdf;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment; filename=\"shipment.pdf\"");
            try {
                IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
                response.flushBuffer();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public byte[] htmlToByte(String html) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont("/fonts/SIMSUN.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        renderer.setDocumentFromString(html);
        renderer.layout();
        renderer.createPDF(outputStream);
        renderer.finishPDF();
        return outputStream.toByteArray();
    }

    /**
     * 编码文件名
     */
    public static String encodingFilename(String filename) {
        filename = UUID.randomUUID() + ".pdf";
        return filename;
    }

    /**
     * 获取下载路径
     *
     * @param filename 文件名称
     */
    public static String getAbsoluteFile(String filename) {
        String downloadPath = BhtmsConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    //PDF文件添加页码
    //给PDF文件添加页码
    public static String addPageNum(String orgPdfPath, String outputPdfPath) throws IOException, DocumentException {
        // 输出文件流
        FileOutputStream fos = new FileOutputStream(outputPdfPath);
        // 新建文档，默认A4大小
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        // 设置页面监听事件，必须在open方法前
        writer.setPageEvent((PdfPageEvent) new PageNumPdfPageEvent());
        document.open();
        // PDF内容体
        PdfContentByte pdfContent = writer.getDirectContent();
        // 读取 源PDF文件，进行一页一页复制，才能触发 添加页码的  页面监听事件
        PdfReader reader = new PdfReader(orgPdfPath);
        // 获取 源文件总页数
        int num = reader.getNumberOfPages();
//        System.out.println("总页数：" + num);
        // 页面数是从1开始的
        boolean pageEmpty = false;
        for (int i = 1; i <= num; i++) {
            document.newPage();
            // 设置空页码进行展示
//            if(i < 4){
//                pageEmpty = true;
//            }

            writer.setPageEmpty(pageEmpty);
            document.setPageCount(num);
            PdfImportedPage page = writer.getImportedPage(reader, i);
            System.out.println("宽度：" + page.getWidth());
            System.out.println("高度：" + page.getHeight());

            // 复制好的页面，添加到内容去，触发事件监听
            pdfContent.addTemplate(page, 0, 0);
        }
        document.close();
        reader.close();
        File file = new File(orgPdfPath);// 读取
        if (file.exists()) {
            file.delete();
        }
        writer.close();
        return outputPdfPath;
    }

    /**
     * 为PDF文件添加页码（已生成的pdf文件）
     */
    public static class PageNumPdfPageEvent extends PdfPageEventHelper {

        public void onEndPage(PdfWriter writer, Document document) {
            try {
                // PDF文档内容
                PdfContentByte pdfContent = writer.getDirectContent();

                pdfContent.saveState();
                pdfContent.beginText();

                int footerFontSize = 12;
                int pageFontSize = 8;
                // 解决页码中文无法显示 或者 显示为乱码的问题
                // 但是必须引入jar包 itext-asian-5.2.0.jar
                BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
                BaseFont bf = BaseFont.createFont("/fonts/SIMSUN.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font fontDetail = new Font(bf, pageFontSize, Font.NORMAL);
                pdfContent.setFontAndSize(baseFont, footerFontSize);
                // 页脚的页码 展示
                String footerNum = "";
//                if(writer.getCurrentPageNumber() > 3){
                footerNum = String.format(String.format("第%d页", writer.getCurrentPageNumber()) + "/共%d页", document.getPageNumber());
//                }

                Phrase phrase = new Phrase(footerNum, fontDetail);

                // 页码的 横轴 坐标 居中
                float x = (document.left() + document.right()) / 2;
                // 页码的 纵轴 坐标
                float y = document.bottom(-10);
                // 添加文本内容，进行展示页码
                ColumnText.showTextAligned(pdfContent, Element.ALIGN_CENTER, phrase, x, y, 0);

                pdfContent.endText();
                pdfContent.restoreState();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
